package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AIService;
import com.xuanzheng.company.service.impl.AIServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/aiUserSearch")
public class AIUserSearchServlet extends HttpServlet {
    
    private final AIService aiService = new AIServiceImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (!isAdmin(request)) {
                result.put("success", false);
                result.put("message", "Access denied");
                out.print(gson.toJson(result));
                return;
            }
            
            String keyword = request.getParameter("keyword");
            
            if (keyword == null || keyword.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "Search keyword is required");
                out.print(gson.toJson(result));
                return;
            }
            
            List<Map<String, Object>> users = aiService.searchUsers(keyword.trim());
            
            result.put("success", true);
            result.put("users", users);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "Internal server error: " + e.getMessage());
        }
        
        out.print(gson.toJson(result));
        out.flush();
        out.close();
    }
    
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) return false;
        
        User user = (User) session.getAttribute("user");
        return user != null && user.getRole() == 2;
    }
}